package com.example.cmh.service.impl;

import com.example.cmh.common.DeleteUtil;
import com.example.cmh.common.UploadUtil;
import com.example.cmh.mapper.TenantMapper;
import com.example.cmh.pojo.Department;
import com.example.cmh.pojo.Tenant;
import com.example.cmh.pojo.User;
import com.example.cmh.service.DepartmentService;
import com.example.cmh.service.TenantService;
import com.example.cmh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户服务实现类
 */
@Service
public class TenantServiceImpl implements TenantService {
    
    @Autowired
    private TenantMapper tenantMapper;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DepartmentService departmentService;
    
    @Override
    public Map<String, Object> getTenants(Integer page, Integer size, String tenantName, String contactPhone, String contactPerson, Integer tenantId, String startTime, String endTime) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取租户列表
        List<Tenant> tenants = tenantMapper.getTenants(offset, size, tenantName, contactPhone, contactPerson, tenantId, startTime, endTime);
        
        // 获取总数
        Integer total = tenantMapper.getTenantsCount(tenantName, contactPhone, contactPerson, tenantId, startTime, endTime);
        
        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", tenants);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        
        return result;
    }
    
    @Override
    @Transactional
    public Tenant addTenants(MultipartFile file, Tenant tenant) {
        // 设置注册时间
        if (tenant.getRegisterTime() == null) {
            tenant.setRegisterTime(new Date());
        }
        String url = null;
        if (!file.isEmpty()) {
            // 上传文件到OSS
            try {
                url = UploadUtil.uploadImage(file);
            } catch (IOException e) {
                return null;
            }
            // 更新数据库中的tenant_icon字段
            tenant.setTenantIcon(url);
        }

        // 新增租户
        tenantMapper.addTenants(tenant);

        // 新增对应的租户部门
        Department department = new Department();
        department.setDepartmentName(tenant.getTenantName());
        department.setSuperiorId(0); // 顶级部门
        department.setDisplaySorting(0);
        department.setDepartmentStatus(0); // 正常状态
        department.setRegisterTime(new Date());

        departmentService.addDepartments(department);

        // 新增对应的管理员用户信息
        User adminUser = new User();
        adminUser.setUserName(tenant.getAdminName());
        adminUser.setUserNickname(tenant.getContactPerson());
        adminUser.setUserPhone(tenant.getContactPhone());
        adminUser.setPassword(String.valueOf(tenant.getTenantId())); // 密码默认为新增后的tenantId
        adminUser.setDepartmentId(department.getDepartmentId());
        adminUser.setUserType(1); // 企业管理员
        adminUser.setUserStatus(0); // 正常状态
        adminUser.setGender(0); // 未知性别
        adminUser.setRegisterTime(new Date());
        
        userService.addUsers(adminUser);
        

        
        return tenant;
    }
    
    @Override
    public void updateTenant(Tenant tenant, MultipartFile file) {
        String url = null;
        if (file!=null) {
            // 上传文件到OSS
            try {
                url = UploadUtil.uploadImage(file);
            } catch (IOException e) {
                return ;
            }
            // 更新数据库中的tenant_icon字段
            tenant.setTenantIcon(url);
        }

        tenantMapper.updateTenant(tenant);
    }
    
    @Override
    public void deleteTenant(Integer tenantId) {
        // 先查出租户信息
        Tenant tenant = tenantMapper.getTenantById(tenantId);
        if (tenant != null) {
            // 删除同名部门
            departmentService.deleteDepartmentByName(tenant.getTenantName());
        }
        // 删除租户
        tenantMapper.deleteTenant(tenantId);
    }

    @Override
    public void deleteIcon(String url) {
        if (url == null || url.isEmpty()) {
            return;
        }
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        DeleteUtil.deleteFile(fileName);
    }
} 